package com.dys.controller;

import com.dys.common.ResponseResult;
import com.dys.utils.Constants;
import com.dys.utils.RedisCache;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 疾风
 * @ClassName: CaptchaController
 * @Description: 生成验证码控制器
 * @CreateDate: 2024/12/18
 * @Version: v1.0.0
 */
@RestController
@RequestMapping(value = "/captcha")
public class CaptchaController {

    @Autowired
    private RedisCache redisCache;

    @GetMapping(value = "/captchaImage")
    public ResponseResult<Map<String, Object>> getCode(HttpServletResponse response) {
        // 三个参数分别为宽、高、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        // 生成验证码,及验证码唯一标识
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String key = Constants.CAPTCHA_CODE_KEY+ uuid;
        String code = specCaptcha.text().toLowerCase();

        // 保存到redis
        redisCache.setCacheObject(key,code,100, TimeUnit.SECONDS);

        // 创建Map
        Map<String, Object> map = new HashMap<>(2);
        map.put("uuid",uuid);
        map.put("img",specCaptcha.toBase64());

        return new ResponseResult<>(200,"获取验证码成功",map);
    }
}
